<?php 
Import::appLibs("Configuration");
class EmployerController extends Controller {
	private $emp_session ;
	public function __construct(){
		$this->calledClass(get_class($this));
		$this->emp_session = Session::get("employer");
	}
	/* Mr. Chamroeun Oum
	 * Function to retrive all employers to build up employers table for ajax call
	*/
	public function employers(){
		$employer = $this->loadModel("Employer");
		//$records = $employer->getList($page=1,$perpage=20,$search="",$searchFields=array(),$sortFields=array(),$sortCriteria="");
		$page = $this->get("page")!=NULL?$this->get("page"):1;
		$perpage = $this->get("perpage")!=NULL?$this->get("perpage"):20;
		$search = $this->get("search")!=NULL?$this->get("search"):"";
		$records = $employer->getList($page,$perpage,$search,array("firstname","lastname","username","email","company_name"),array());
		$this->set(array("records"=>$records));
		$this->render("admin_display");
	}
	public function admin(){
		$saveresume = $this->loadModel("SaveResume");
		$category = $this->loadModel("Categorie");
		$memebership = $this->loadModel("Membership");
		$employer = $this->loadModel("Employer");
		$gallery = $this ->loadModel("Gallery");
		$emp_info = $employer->findObject(array("id="=>$this->emp_session["id"]));
		$this->set(array("employer"=>$emp_info));
		$this->set(array("emp_imgs"=>$gallery->findObject(array("id="=>$emp_info->img_id))));
		//display follow resume
		$this->set(array("follow_resume_lst"=>$memebership->get_follow_resume_list($this->emp_session["id"],1,4,array(),array())));
		
		$this->set(array("Experiences"=>$category->SelectQu(333)));
		$this->set(array("Position"=>$category->SelectQu(137)));
		$this->set(array("Location"=>$category->SelectQu(1)));
		$this->set(array("HighEducation"=>$category->SelectQu(143)));
		$this->set(array("Getallcate"=>$saveresume->SelectC()));
		//display Favourite Resumes
		$this->set(array("resumes"=>$saveresume->getPage($this->emp_session["id"],1,4,array(),array())));
		
		$job = $this->loadModel("Job");
		//display Published Jobs
		$this->set(array("jobs"=>$job->getPage($this->emp_session["id"],1,4,array(),array())));
		
		$category = $this->loadModel("Categorie");
		$categories = $category->getCategoriesAsArray();
		$this->set(array("categories"=>$categories));
		$applyjob = $this->loadModel("NotiApplie");
		//display Applications
		$this->set(array("appyJob"=>$applyjob->getPageEmployer($this->emp_session["id"],1,10,array("date_apply"),"DESC")));
	
		$order = $this->loadModel("Order");
		$this->set(array("orderPackages"=>$order->getPage($this->emp_session["id"],"Package",1,4,array(),array())));
		$this->set(array("orderSubscriptions"=>$order->getPage($this->emp_session["id"],"Subscription",1,4,array(),array())));
		
		$membership = $this->loadModel("Membership");
		$valmembership = $membership->getData($this->emp_session["id"]);
		if(is_object($valmembership)){
			//This employer is a membership
			$valmembership = isset($valmembership)&&is_object($valmembership)?$valmembership->user_id:NULL;
			$this->set(array("point"=>$membership->findAsObject(array("user_id="=>$valmembership,"sub_type="=>"Employer"))));
			$this->set(array("subscriptionexpire"=>$membership->findAsObject(array("user_id="=>$valmembership))));
		}else{
			// this employer is not a membership
			$this->set(array("point"=>0));
			$this->set(array("subscriptionexpire"=>""));
		}
		$this->render("admin");
	}
	public function registerPage(){
		$this->render("register");
	}
	public function resetPage(){
		@$recordEmp = @$this->model->findAsObject(array("id="=>$this->get("empId")));
		if(@$recordEmp->link_expire > date("Y-m-d H:i:s")){
			$this->set("recordEmp",@$recordEmp);
			$this->render("reset");
		}else{
			$this->render("link_expire");
		}
	}
	public function newPasswordForgot(){
		$employer = $this->loadModel("Employer");
		if($this->get("newpwd")==$this->get("confirmpwd")){
			$row = $employer->update(array("password"=>md5($this->get("newpwd"))
			),array("id="=>$this->get("empId")));
			echo 1;
		}
	}
	public function loginPage(){
		$this->set(array("title"=>"Employer Login | HR Cambodia - The best website to find job","active_menu"=>"emploginpage" ));
		$this->render("login");
	}
	public function forgotPage(){
		$this->render("forgot");
	}
	public function accountPage(){
		$employer = $this->loadModel("Employer");
		$gallery = $this->loadModel("Gallery");
		$emp_info = $employer->findObject(array("id="=>$this->emp_session["id"]));
		$this->set(array("employer"=>$emp_info));
		$emp_location = $gallery->findObject(array("id="=>$emp_info->img_id)) ;
		$this->set(array("images"=>$emp_location));
		$img_location = is_object($emp_location)?ROOT.$emp_location->location:"";
		$this->set(array("img_location"=>$img_location));
		$this->set(array("layout"=>"account") );
		$this->render("admin");
	}
	public function admindetail(){
		if($this->get("id")!=NULL){
			$employer = $this->loadModel("Employer");
			$job = $this->loadModel("Job");
			$this->set("emp_id",$this->get("id") );
			// update field admin_view after super admin view it already
			$employer->update(array("admin_view"=>1),array("id = "=>$this->get("id")));
			$jobs = $job->getEmployerJobs($this->get("id"),1,4,"",array("id"),array("id"),"DESC");
			$this->set(array("jobs"=>$jobs));
			$this->set(array("employer"=>$employer->findObject(array("id="=>$this->get("id")))));
			$this->render("admin_detail");
		}else{
			echo "Please specify id of employer";
		}
	}
	/*
	* @Developer: Dim Sidet
	* @Create Modify: 1-May-2014
	* @Return username,password,and status
	* */
	public function login(){
		$employer = $this->loadModel("User");
		$job = $this->loadModel("Job");
		$config = $this->loadModel("Config");
		$emp = $this->loadModel("Employer");
		$config = $config->findAsObject(array("id="=>1));
		$result = $employer->checkRecord("Employers",array("username","password"),array("username="=>$this->get("username"),"password="=>md5($this->get("password")),"status="=>1));
		if($result){
			//$sessionId = $employer->getFieldValue("Sessions",array("sessionid"),array("userid"=>$this->get("username"),"ip"=>$_SERVER['REMOTE_ADDR'],"ORDER BY logged "=>"","LIMIT 0,1"=>""),"");
			//$sessionId = is_array($sessionId)&&!empty($sessionId)?$sessionId[0]->sessionid:null;
			$sessionId = $employer->getSessionId($this->get("username"),$_SERVER['REMOTE_ADDR']);
			if(!Session::exist("employer")){
				$id=$employer->getFieldValue("Employers",array("id"),array("username="=>$this->get("username"),"password="=>md5($this->get("password"))));
				Session::set("employer" ,array(
					"id"=>is_array($id)&&!empty($id)?$id[0]->id:0,
					"session"=> $sessionId ,
					"user" => $this->get("username")
				));
				$session = Session::get("employer");
				$employer->saveUserSession(array(
					"sessionid"=>md5(time().$session["user"].$_SERVER["REMOTE_ADDR"]),
					"version"=>1,
					"logged"=>date("Y-m-d H:i:s"),
					"ip"=>$_SERVER["REMOTE_ADDR"],
					"userid"=>$session["user"],
					"type"=>Configuration::getNodeValue("Employer_Type"),
					"duration"=>$config->duration . "mn"
				));
				$login_count = $emp->getValue("Employers",array("login_count"),array("id="=>$session['id']));
				$emp->update(array("login_date"=>date("Y-m-d H:i:s"),"login_count"=>$login_count[0]->login_count+1),array("id="=>$session['id']),"");
				$this->redirect(array("employer"=>"index"));
			}else{
				$check=$employer->checkSession($sessionId,$_SERVER["REMOTE_ADDR"]);
				$check?$this->logout():$this->redirect(array("employer"=>"index"));
			}
		}else{
			$this->redirect(array("employer"=>"loginpage"),array("emp_login_err"=>"Username and Password wrong !"));
		}
	}
	/*  
	 * @Developer: vitou
	 * @Create Modify: 20-May-2014
	 * @Return check usernam
	 * */
	public function checkUserNameEm(){
		$employer = $this->loadModel("Employer");
		$checkusername = $employer->getUserNameEmp($this->get("username"));
		if($checkusername==$this->get("username")){
			echo "ok";
		}elseif($checkusername!=$this->get("username")){ 
			echo "no";
		}elseif($checkusername==""){
			echo 0;
		}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
         /*  
	 * @Developer: vitou
	 * @Create Modify: 20-May-2014
	 * @Return check usernam
	 * */
	public function checkEmailEm(){
		$employer = $this->loadModel("Employer");
		$email = $employer->checkCanEmail($this->get("email"));
		if($email==$this->get("email")){
			echo "ok";
		}elseif($email!=$this->get("email")){ 
			echo "no";
		}elseif($email==""){
			echo 0;
		}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
	/*  
	 * @Developer: Dim Sidet
	 * @Create Modify: 1-May-2014
	 * @Return check mail
	 * */
	public function checkMailForgetPasswod(){
		$employer = $this->loadModel("Employer");
		$checkmail = $employer->checkCanEmail($this->get("email"));
		if($checkmail==$this->get("email")){
			echo "ok";
		}elseif($checkmail!=$this->get("email")){ 
			echo "no";
		}elseif($checkmai==""){
			echo 0;
		}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
	/*
	 * @Develope by : Dim sidet
	* @Create Date : 1-May-2014
	* @Return : ramdom character
	*  */
	public function updateStatusRegisterToLogin(){
		$employer = $this->loadModel("Employer");
		$employer->update(array("status"=>1),array("activated="=>trim($this->get("activated"))));
		$this->redirect(array("employer"=>"loginpage"));
	}
	/*
	* @Develope by : Dim sidet
	* @Create Date : 1-May-2014
	* @Return : ramdom character
	*  */
	function random($length=10) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$size = strlen($chars);
		$str = '';
		for ($i = 0; $i < $length; $i++) {
			$str .= $chars[rand(0, $size - 1)];
		}
		return $str;
	}
	public function registerAjax(){
		$result = array("error"=>"1","message"=>"Failed to login.");
		$employer = $this->loadModel("Employer"); 
		/*
		$em = $employer->getEmailEm();
		foreach ($em as $emailall){
			if($emailall->email==trim($this->get("email"))){
				$this->refresh(array("employer"=>"loginpage"),3);
				echo "Your email is already exist. you will be redirected to the login page within 3 seconds" ;
				exit();
				}
		}*/
		$user_enter = $this->get("captcha");
		$captcha = Session::get("vercode");
		if($user_enter == $captcha){
			$recordEmp = $employer->save(array(
					"firstname"=>$this->get("firstname"),
					"lastname"=>$this->get("lastname"),
					"username"=>$this->get("username"),
					"password"=>md5($this->get("password")),
					"email"=>$this->get("email"),
					"company_name"=>$this->get("business"),
					//"activated"=>trim($activate),
					//"address"=>$this->get("address"),
					"admin_view"=> 0,
					"signup_date"=>date("Y-m-d H:i:s"),
					"ip"=>$_SERVER['REMOTE_ADDR'],
					"status"=>1,
					"version"=>1));
			/*
			//Send mail to surper admin and Candidate after candidate register already
			$baseURL= SERVER.ROOT."index.php/employer/activate/activated:" . $activate;
			$arrMail = array($recordEmp->email,"phonpisey23@gmail.com");
			$strEmp = "Welcome to HRCambodia!<br/>";
			$strEmp.="Thanks you for register! <br/>";
			$strEmp.="To active you account for login,Please <a href='".$baseURL."'>click to here</a><br/>";
			$strSuperAdmin = "Here is the one who just registered with our company!<br/>";
			$strSuperAdmin .="Name : " .$recordEmp->firstname ." ". $recordEmp->lastname ."<br/>";
			$strSuperAdmin .="Name of Company : " .$recordEmp->company_name ."<br/>";
			$strSuperAdmin .="Email : " .$recordEmp->email ."<br/>";
			$arrStr = array($strEmp,$strSuperAdmin);
			$arrSub = array("HRCambodia Alert Information","HRCambodia Alert Information");
			ob_start();
			//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
			Import::util('class.phpmailer');
			//the true param means it will throw exceptions on errors, which we need to catch
			$mail = new PHPMailer(true);
			//telling the class to use SMTP
			$mail->IsSMTP();
			try {
				// SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
				$mail->SMTPDebug = 1;
				// enable SMTP authentication
				$mail->SMTPAuth = true;
				// sets the SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// set the SMTP port for the MY OWN DOMAIN server
				$mail->Port = 25;
				// SMTP account username
				$mail->Username = "demo@atmos-techno.com";
				// SMTP account password
				$mail->Password = "demo*123456";
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				for($i=0;$i<count($arrMail);$i++){
					// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
					$mail->AddAddress($arrMail[$i], 'HRCambodia');
					//$mail->AddAddress('phonpisey23@gmail.com','');
					$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
					$mail->Subject = "HRCambodia Alert " . $arrSub[$i];
					// optional - MsgHTML will create an alternate automatically
					$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
					$mail->MsgHTML($arrStr[$i]."<br/>");
					$mail->Send();
					$mail->ClearAddresses();
					$mail->ClearAttachments();
				}
			} catch (phpmailerException $e) {
				//Pretty error messages from PHPMailer
				echo $e->errorMessage();
			} catch (Exception $e){
				//Boring error messages from anything else!
				echo $e->getMessage();
			}
			*/
			Session::set("user",$recordEmp);
			//["error"]=0;
			//$result["message"]="Successfully login !!!";
			//$this->redirect(array("employer"=>"loginpage"));
			$this->refresh(array("employer"=>"loginpage"),array(),3);
			echo "You have registered successlly. you will be redirected to login's page within 3 seconds. ! ";
		}else{
			$this->redirect(array("employer"=>"registerpage"),array("err"=>"Incorrect verification code,Try again",3));
		}
		//echo "(".json_encode($result).")";
	}
	public function messageActivate(){
		$this->render("activate_message");
	}
	public function save(){
		$employer = $this->loadModel("Employer");
		$employer->save(array(
			"firstname"=>$this->get("firstname"),
			"lastname"=>$this->get("lastname"),
			"username"=>$this->get("username"),
			"password"=>md5($this->get("password")),
			"email"=>$this->get("email"),
			"company_name"=>$this->get("business"),
			"created"=>date("Y-m-d H:i:s"),
			"signupdate"=>date("Y-m-d H:i:s"),
			"version"=>1
			));
	}
	public function update(){
		$employer = $this->loadModel("Employer");
		$user = $this->loadModel("User");
		$gallery = $this->loadModel("Gallery");
		
		$vers = $employer->getObject(array("id="=>$this->emp_session["id"]));
		$getFieldEmp = $employer->getImgEmployer($this->emp_session["id"]);//check employer img_id
		
		$row = $employer->update(array(
			"firstname"=>$this->get("firstname"),
			"lastname"=>$this->get("lastname"),
			"username"=>$this->get("username"),
			"company_name"=>$this->get("business"),
			"about_me"=>$this->get("aboutme"),
			"email"=>$this->get("email"),
			"version"=>$vers->version+1,//$user->getValue("Employers","version",array("id="=>$this->emp_session["id"])) + 1,
			"modified"=>date("Y-m-d H:i:s")
			//"modified_by"=>Session::get("employer_name")
			),array("id="=>$this->emp_session["id"])
		);
		//update photo
		$folder = "data/pp" ;
		//if(!Basic::fileExist($folder))Basic::createFolder($folder);
		Import::util("FileUpload");
		$infos=FileUpload::checkFileUpload($folder);
		$helper = true; 
		foreach($infos AS $info ){
			if($info["name"] != NULL){
				if($info["error"]["number"]==0){
					if($getFieldEmp ==0 ){//if employer has no photos
						if(($record=$gallery->savephoto(array(
								"name"=>$info["name"],
								"location"=>$folder."/".$info["base64"].".".$info["ext"],
								"type"=>$info["type"],
								"size"=>$info["size"],
								"d_w"=>$info["dimension"]["width"],
								"d_h"=>$info["dimension"]["height"],
								"created"=>date("Y-m-d H:s:i"))))!==false){
								$gallery->update(array("location"=>$folder."/".$record->id.".".$info["ext"]),array("id="=>$record->id));
								//$ids[]=$record->id;
								
								FileUpload::uploadFile($info["control"],$record->id.".".$info["ext"],5,$folder);
								$employer->update(array("img_id"=>$record->id),array("id="=>$this->emp_session["id"]));
								
								$this->redirect(array("employer"=>"account"));
						}else{
							Basic::eco("<br/>There is an unexpected error occured during upload file.<br/>");
							//Basic::pr($info);
							$help=false;
						}
						//if($this->get("ajax")==NULL)$this->redirect(array("employer"=>"index"));
						//else echo 1;
					}elseif($getFieldEmp){
						//if employer has photo already
						$image = $gallery->findObject(array("id="=>$row->img_id));
						Basic::deleteFile($image->location);
						if(($record=$gallery->update(array("name"=>$info["name"],
								"location"=>$folder."/".$row->img_id.".".$info["ext"],
								"type"=>$info["type"],
								"size"=>$info["size"],
								"d_w"=>$info["dimension"]["width"],
								"d_h"=>$info["dimension"]["height"],
								"uid"=>$this->emp_session["id"],
								"user_type"=>"employer",
								"modified"=>date("Y-m-d H:i:s")),array("id="=>$row->img_id)))!==false){
								FileUpload::uploadFile($info["control"],$row->img_id.".".$info["ext"],5,$folder);
								$this->redirect(array("employer"=>"index"));
						}else{
							Basic::eco("<br/>There is an unexpected error occured during upload file.<br/>");
							Basic::pr($info);
							$help=false;
						}
					}else{
						// check error
					}
				}
			}else{
			}
			$this->redirect(array("employer"=>"account"));
			//if($this->get("ajax")==NULL)$this->redirect(array("employer"=>"index"));
			//else echo 1;
		}
	}
	
	public function reset(){
		$employer = $this->loadModel("Employer");
		$user = $this->loadModel("User");
		@$vers = $employer->getObject(array("id="=>$this->emp_session["id"]));
		@$version = @$vers->version+1;//$user->getValue("Employers","version",array("id="=>$this->emp_session["id"])) + 1;
		//check the old password existed or not
		@$result = @$user->checkRecord("Employers",array("password"),array("username="=>$this->get("ajax")==1?$this->get("username"):Session::get("employer_name"),"password="=>md5($this->get("oldpwd"))));
		if($result){
			if($this->get("newpwd")==$this->get("confirmpwd")){
				$employer->update(array("password"=>md5($this->get("newpwd")),"version"=>@$version),array("id="=>$this->emp_session["id"]));
				if($this->get("ajax")==1){
					echo 1;
				}else{
					$this->redirect(array("employer"=>"loginpage"));
				}
			}else{
				$this->set(array("pwderr"=>"Password missmacth !"));
				$this->redirect(array("employer"=>"loginpage")); 
			}
		}else{
			if($this->get("ajax")==1){
				echo 0;
			}else{
				$this->set(array("incorrect"=>"Incorrect old password"));
				$this->redirect(array("employer"=>"resetpage"));
			}
		}
	}
	public function resetFromMail(){
		$candidate = $this->loadModel("Employer");
		$user = $this->loadModel("User");
		$recordEmp = $this->model->findAsObject(array("id="=>$this->get("empId")));
		//check is the old password is existed or not ?
		$result = $user->checkRecord("Employers",array("password"),array("username="=>$recordEmp->username,"password="=>$recordEmp->password,"email="=>$recordEmp->email));
		$version = $user->getRecords(array("version"),array("id="=>$recordCan->id)) + 1;
		if($result){
			if($this->get("newpwd")==$this->get("confirmpwd")){
				$candidate->update(array("password"=>md5($this->get("newpwd")),"version"=>$version,"modified"=>date("Y-m-d H:i:s")),array("id="=>$recordEmp->id));
				if($this->get("ajax")==1){
					echo 1;
				}else{
					$this->redirect(array("employer"=>"loginpage"));
				}
			}else{
				//print_r($recordEmp->id);
				$this->set(array("incorrect"=>"Password is missmatch !"));
				$this->redirect(array("employer"=>"resetpage"),array("empId"=>$recordEmp->id));
			}
		}else{
			if($this->get("ajax")==1){
				echo 0;
			}else{
				$this->set(array("incorrect"=>"Incorrect old password"));
				$this->redirect(array("employer"=>"resetpage"),array("empId"=>$recordEmp->id));
			}
		}
	}
	public function delete(){
		$employer = $this->loadModel("Employer");
		$remove = $employer->delete(array("id="=>$this->emp_session["id"]));
	}
	public function logout(){
		$employer = $this->loadModel("Employer");
		$employer->update(array("logout_date"=>date("Y-m-d H:i:s"),array("id="=>$this->emp_session['id'])));
		//Session::destroy();
		Session::kill("employer");
		//$this->sendExpireJobToEmployee();
		$this->redirect(array("employer"=>"loginpage"));
	}
	public function sendExpireJobToEmployee(){
		$job = $this->loadModel("Job"); 

		/* staring of job has been expired  */
		$current_date = date('Y-m-d H:i:s');
		$cur_date=strtotime($current_date);
		$deadline=$job->getExpiredToEmployee();
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
		// SMTP server
		$mail->Host = "mail.atmos-techno.com";
		// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
		$mail->SMTPDebug = 1;
		// enable SMTP authentication
		$mail->SMTPAuth = true;
		// sets the SMTP server
		$mail->Host = "mail.atmos-techno.com";
		// set the SMTP port for the MY OWN DOMAIN server
		$mail->Port = 26;
		// SMTP account username
		$mail->Username = "demo@atmos-techno.com";
		// SMTP account password
		$mail->Password = "demo*123456";
		//$mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
		//$mail->AddAddress('physopheak10@gmail.com', '');
		//$mail->AddAddress('phonpisey23@gmail.com','');
		//date("d-M-Y",strtotime($exp->post_date));
		//date("d-M-Y",strtotime($exp->expire_date));
		foreach($deadline as $exp){
			$email_address = filter_input(INPUT_GET, $exp->eemail, FILTER_VALIDATE_EMAIL);
		}
		if (!$email_address) {
			foreach($deadline as $exp){
				$exp_date=strtotime($exp->expire_date);
				if($cur_date > $exp_date){
					$job->updateExpireJob();
					$str = "<b>Your HRCambodia .com Daily Job Alert</b><br/>";
					$str .="<br/><span style='font-family: Trebuchet MS;padding-right:5px'>Post date: " . date('d-M-Y',strtotime($exp->post_date)) ."</span>";
					$str .="<br/><span style='font-family: Trebuchet MS'>Title: " . $exp->title ."</span>";
					$str .="<br/><span style='font-family: Trebuchet MS;padding-right:5px'>Expire date: " . date('d-M-Y',strtotime($exp->expire_date)) ."</span>";
					$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
					$mail->AddAddress($exp->eemail, ' ');
					$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
					$mail->Subject = "Job has been expired !";
					// optional - MsgHTML will create an alternate automatically
					$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
					$mail->MsgHTML($str . "<br/>");
					$mail->Send();
					$mail->ClearAddresses();
				}
			}
		} else {
		echo 'Email is invalid...';
		break;
		}
			
			
		} catch (phpmailerException $e) {
		//Pretty error messages from PHPMailer
		echo $e->errorMessage();
		} catch (Exception $e) {
		//Boring error messages from anything else!
		echo $e->getMessage();
		}

		/* ending of job has been expired  */
	}
	/* Developer:Mr.Dim sidet 
	 * Date Modyfy: 18-March-2014
	 * Return: show all job by employee login to 
	 * Starting of show job has been save in employee login */
	public function jobView(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$member = $this->loadModel("Membership");
		$employer = $this->loadModel("Employer");
		$gallery = $this ->loadModel("Gallery");
		$jobtitle=urldecode($this->get("jobtitle"));
		$jobcat=urldecode($this->get("jobcat"));
		$joblocation=urldecode($this->get("joblocation"));
		$jobtype=urldecode($this->get("jobtype"));
		$checkpoint = $member->findAsObject(array("user_id="=>$this->emp_session["id"],"sub_type="=>"Employer"));
		if($checkpoint){
			$this->set("posting_point",$checkpoint->posting_point);
		}else{
			$this->set(array("posting_point"=>0));
		}
		
		
		if($jobcat){
			$jobcat=str_replace("%2F","/",$jobcat);
			$jobcat=str_replace("%20"," ",$jobcat);
		}
		if($joblocation){
			$joblocation=str_replace("%2F","/",$joblocation);
			$joblocation=str_replace("%20"," ",$joblocation);
		}
		if($jobtype){
			$jobtype=str_replace("%2F","/",$jobtype);
			$jobtype=str_replace("%20"," ",$jobtype);
		}
		
		$this->set(array("premium_post"=>5));
		
		$emp_info = $employer->findObject(array("id="=>$this->emp_session["id"]));
		$this->set(array("employer"=>$emp_info));
		$this->set(array("emp_imgs"=>$gallery->findObject(array("id="=>$emp_info->img_id))));
		$query = $post->QueryFront($this->emp_session["id"]);
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		$this->set(array("list"=>$post->PaginationFrontJob($query,$this->get("page"),20,$jobtitle,$jobcat,$joblocation,$jobtype,array("id"),"DESC")));
		$this->set(array("urls"=>array("jobcat"=>$jobcat,"jobtitle"=>$jobtitle,"joblocation"=>$joblocation,"jobtype"=>$jobtype)));
		/* get all number of records from job table  */
		$this->set(array("getRow"=>$post->GetPostByEmpId($this->emp_session["id"])));
		///get user_id from url and set back to view
		$this->set(array("user_id"=>$this->emp_session["id"]));
		$this->set(array("layout"=>"job"));
		$this->render("admin");
	}
	
	
	/*  Ending of show job has been save in employee login */
	/*  */
	public function ChoosePosting(){
		$post = $this->loadModel("Post");
		$membership= $this->loadModel("Membership");
		$user= $this->loadModel("User");
		$getfirstid = $post->getData($this->get("emp_id"));
		$getfirstid = isset($getfirstid->emp_id)?$getfirstid->emp_id:NULL;
		$test = $this->set(array("queryEmpId"=>$user->getValue("Employers","id",array("id="=>$this->get("emp_id")))));
		$valpointexpire = $membership->GetSubscription("Memberships","point_expire",array("user_id="=>$getfirstid));
		if ($valpointexpire <= date("Y-m-d H:i:s") && $valpointexpire != 0){
			$this->set(array("point"=>$membership->GetPostingPoint("Memberships","posting_point",array("user_id="=>$getfirstid))));
			$this->set(array("layout"=>"pointexpire"));
			$this->render("admin");
		}else{
			$this->set(array("layout"=>"choosepost"));
			$this->render("admin");
		}
	}
	public function PostJob(){
		$post = $this->loadModel("Post");
		$job = $this->loadModel("Job");
		$package= $this->loadModel("Package");
		$membership= $this->loadModel("Membership");
		$order= $this->loadModel("Order");
		$user= $this->loadModel("User");
		$getfirstid = $membership->getData($this->get("emp_id"));
		$getfirstid = isset($getfirstid->user_id)?$getfirstid->user_id:NULL;
		$where = $post->PostJob();
		$category=$this->loadModel("Categorie");
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		if($this->get("type")=="premium"){
			$result = $post->CountPostingPoint($this->get("emp_id"));
			$cutpoint = $result -1;
			$countposting = $post->CuttingPoint($cutpoint,$getfirstid);
			if($countposting > 0){
				$post->save(array(
						"job_id"=>$_SESSION["job_id"],
						"emp_id"=>$this->get("emp_id"),
						"post_date"=>date("Y-m-d H:i:s"),
						"type"=>$this->get("type"),
						"version"=>1,
						"created"=>date("Y-m-d H:i:s")));
				$query = $post->QueryFront($this->get("emp_id"));
				$job->edit(array("publish"=>1),array("id = "=>$_SESSION["job_id"]));
				$this->set(array("list"=>$post->PaginationFront($query,$this->get("page"),15,array("job_categories"=>$this->get("jobcat"),"title"=>$this->get("jobtitle"),"location"=>$this->get("joblocation"),"job_time"=>$this->get("jobtype")),array("created"),"DESC","AND")));
				$this->set(array("urls"=>array("jobcat"=>$this->get("jobcat"),"jobtitle"=>$this->get("jobtitle"),"joblocation"=>$this->get("joblocation"),"jobtype"=>$this->get("jobtype"))));
				$this->set(array("getPost"=>$post->GetPost($this->get("emp_id"))));
				$this->set(array("getRow"=>$post->GetPostByEmpId($this->emp_session["id"])));
				///get emp_id from url and set back to view
				$this->set(array("emp_id"=>$this->get("emp_id")));
				// Update the publish field in table job
				$job->edit(array("publish"=>1),array("id = "=>$_SESSION["job_id"]));
				
				
				$this->set(array("layout"=>"job"));
				$this->render("admin");
				
				
			}else {
				$this->set(array("querypackage"=>$package->DisplayFront()));
				$this->set(array("point"=>$membership->GetPostingPoint("Memberships","posting_point",array("user_id="=>$this->get("emp_id")))));
				$this->set(array("layout"=>"package"));
				$this->render("admin");
			}
		}else{
			$countposting = $post->CountPosting($this->get("emp_id"));
			$standard_posting = Configuration::getNodeValue("Standard_Post");
			/*Get Point of employer to show in front_choose_choice*/
			$this->set(array("point"=>$membership->GetPostingPoint("Memberships","posting_point",array("user_id="=>$getfirstid))));
			$point = $membership->GetPostingPoint("Memberships","posting_point",array("user_id="=>$getfirstid));
			if($countposting < $standard_posting){
				$post->save(array(
						"job_id"=>$_SESSION["job_id"],
						"emp_id"=>$this->get("emp_id"),
						"post_date"=>date("Y-m-d H:i:s"),
						"type"=>$this->get("type"),
						"version"=>1,
						"created"=>date("Y-m-d H:i:s")));
				$query = $post->QueryFront($this->get("emp_id"));
				$this->set(array("list"=>$post->PaginationFront($query,$this->get("page"),15,array("job_categories"=>$this->get("jobcat"),"title"=>$this->get("jobtitle"),"location"=>$this->get("joblocation"),"job_time"=>$this->get("jobtype")),array("created"),"DESC","AND")));
				$this->set(array("urls"=>array("jobcat"=>$this->get("jobcat"),"jobtitle"=>$this->get("jobtitle"),"joblocation"=>$this->get("joblocation"),"jobtype"=>$this->get("jobtype"))));
				$this->set(array("getPost"=>$post->GetPost($this->get("emp_id"))));
				///get emp_id from url and set back to view
				$this->set(array("emp_id"=>$this->get("emp_id")));
				// Update the publish field in table job
				//print_r($_SESSION["job_id"]);
				$job->edit(array("publish"=>1),array("id="=>$_SESSION["job_id"]));
				$this->set(array("getRow"=>$post->GetPostByEmpId($this->emp_session["id"])));
				$this->set(array("layout"=>"job"));
				$this->render("admin");
			}else{
				if($point > 0){
					$test = $this->set(array("queryEmpId"=>$user->getValue("Employers","id",array("id="=>$this->get("emp_id")))));
					$this->set(array("layout"=>"choosechoice"));
					$this->render("admin");
				}else {
					$this->set(array("querypackage"=>$package->DisplayFront()));
					$this->set(array("layout"=>"buypackage"));
					$this->render("admin");
				}
			}
				
		}
	}
	/**
	 * Edit By Pisey
	 * modified by chamnan 
	 */
	//public function publish(){
		/* starting of load model  */
	/*	$job = $this->loadModel("Job");
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");*/
		/* Developer: Dim sidet
		* Create Date: 24-March-2014
		* Return : if type login is premium provide number 2. but number 1
		*/
		
		/*if($this->get("publish") == "Y"){
			//Publish
			echo 1;
			$job->edit(array("publish"=>$this->get("publish")),array("id="=>$this->get("jid")));*/
			/* get auto job  */
			//$this->autoApprove($this->get("jid"));
			//Send mail to super admin
			/*$this->publicJobPostSendMail($this->get("jid"));
		}else{
			//Unpublish
			$job->edit(array("publish"=>$this->get("publish")),array("id="=>$this->get("jid")));
		}
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
	}*/
	/**
	 * modified by : Mr.chamnan
	 * date: 2014-05-02
	 */
	public function publish(){
		$job = $this->loadModel("Job");
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$job->edit(array("publish"=>"N"),array("id="=>$this->get("jid")));
		/* get auto job  */
		//$this->autoApprove($this->get("jid"));
		//Send mail to super admin
		$this->publicJobPostSendMail($this->get("jid"));
		
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
	}
	/* @Develope by: Dim sidt 
	 * @Create date : 8-April-2014
	 * @Return auto approve
	 * */
	public function autoApprove($jid){
		$job = $this->loadModel("Job");
		$approve=$job->getApproveJob($jid);
		$publish_date=$job->getPublisJob($jid);
		if($approve=="N" && $publish_date==NUll ){
			$job->edit(array("approved"=>"Y","publish_date"=>date("Y-m-d")),array("id="=>$jid));
		}
	}
	public function publicJobPostSendMail($jid){
		$job = $this->loadModel("Job");
		$publicjob=$job->getPublicSendMailToAdmin($jid);
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			$email_address = filter_input(INPUT_GET, "phonpisey23@gmail.com", FILTER_VALIDATE_EMAIL);
			if (!$email_address){
				$str = "<b>Your HRCambodia .com Daily Job Alert</b><br/>";
				$str .="<br/><span style='font-family: Trebuchet MS;padding-right:5px'>Company Name: " . $publicjob->posted_by ."</span>";
				$str .="<br/><span style='font-family: Trebuchet MS;padding-right:5px'>Publish Date: " . date('d-M-Y',strtotime($publicjob->posting_date)) ."</span>";
				$str .="<br/><span style='font-family: Trebuchet MS'>Title: " . $publicjob->title ."</span>";
				$str .="<br/><span style='font-family: Trebuchet MS'>Username: " . $publicjob->username ."</span>";
				$str .="<br/><span style='font-family: Trebuchet MS'>Telephone: " . $publicjob->telephone ."</span>";
				$str .="<br/><span style='font-family: Trebuchet MS'>Email: " . $publicjob->eemail ."</span>";
				$mail->SetFrom($publicjob->eemail,"$publicjob->posted_by Company has been published job!");
				$mail->AddAddress("phonpisey23@gmail.com", 'HRCambodia .com ');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "Job has been publish !";
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML($str . "<br/>");
				$mail->Send();
				//$mail->ClearAddresses();
			} else {
				echo 'Email is invalid...';
				break;
			}	
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			echo $e->getMessage();
		}
	}
	/*
	 * Developer: Dim sidet
	* Create Date: 24-March-2014
	* return : cut point when post job no free
	*  */
	public function cutPoint(){
		$membership= $this->loadModel("Membership");
		$config= $this->loadModel("Config");
		$totalpoint=$membership->getMemberShipPoint($this->emp_session["id"]);
		$pointcut=$config->getAdminCutPoint();
		$totolpointcut=intval($totalpoint)-intval($pointcut);
		$membership->update(array( "posting_point"=>$totolpointcut ),array("user_id="=>$this->emp_session["id"]) );
	}
	public function Subscript(){
		$membership = $this->loadModel("Membership");
		$resume = $this->loadModel("Resume");
		$employer = $this->loadModel("Employer");
		$id = $this->get("id");
		$getResume = $resume->findArray(array("id = "=>$id));
		$valmembership = $membership->findObject(array("user_id = "=>$this->emp_session["id"],"sub_type="=>"Employer","cat_id ="=>$getResume["rem_cat"]));
		$membershipId = isset($valmembership->user_id)?$valmembership->user_id:NULL;
		$membershipCat = isset($valmembership->cat_id)?$valmembership->cat_id:NULL;
		$getOldField = $membership->findObject(array("user_id = "=>$this->emp_session["id"],"sub_type="=>"Employer"));
		$getOldId = isset($getOldField->user_id)?$getOldField->user_id:NULL;
		$getOldCat = isset($getOldField->cat_id)?$getOldField->cat_id:NULL;
		if($membershipId == NULL && $membershipCat == NULL){
			if($getOldId == $this->emp_session["id"]){
				if($getOldCat){
					$getData = $membership->save(array("user_id"=>$this->emp_session["id"],"cat_id"=>$getResume["rem_cat"],"sub_type"=>"Employer","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				echo 1;
				}else{
					//$membership->save(array("user_id"=>$this->emp_session["id"],"cat_id"=>$getResume["rem_cat"],"sub_type"=>"Employer","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
					$getData = $membership->update(array("cat_id"=>$getResume["rem_cat"]),array("user_id = "=>$this->emp_session["id"]));
					echo 1;
				}
			}else{
				$getData = $membership->save(array("user_id"=>$this->emp_session["id"],"cat_id"=>$getResume["rem_cat"],"sub_type"=>"Employer","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				echo 1;
			}
		}else{
			
			if($membershipId == $this->emp_session["id"] && $membershipCat == $getResume["rem_cat"]){
				//Sth happen
				$getData = "";
			}else{
				echo 1;
				$getData = $membership->save(array("user_id"=>$this->emp_session["id"],"cat_id"=>$getResume["rem_cat"],"sub_type"=>"Employer","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
			}
		}	
	}
	public function follow(){
		$membership = $this->loadModel("Membership");
		$resume = $this->loadModel("Resume");
		$employer = $this->loadModel("Employer");
		$candidate = $this->loadModel("Candidate");
		$id = $this->get("id");
		$getResume = $resume->findArray(array("id = "=>$id));
		$record = $membership->findAsObject(array("user_id = "=>$this->emp_session["id"],"sub_type="=>"Employer"));
		if(is_object($record)){
			$version = $membership->findAsObject(array("user_id = "=>$this->emp_session["id"],"sub_type="=>"Employer"));
			$getData = $membership->update(array("resume_id"=>$getResume["id"],"version"=>$version->version + 1,"modify"=>date("Y-m-d H:i:s")),array("user_id = "=>$this->emp_session["id"],"sub_type = "=>"Employer"));
			echo 1;
		}else{
			$getData = $membership->save(array("user_id"=>$this->emp_session["id"],"resume_id"=>$getResume["id"],"sub_type"=>"Employer","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
			echo 1;
		}
		/*
		//Send mail to Employer and Candidate when candidate update Resume
		$recordResume = $resume->findAsObject(array("id = "=>$getData->resume_id));
		//find one record of employer
		$recordEmp = $employer->findAsObject(array("id = "=>$getData->user_id));
		//find one record of candidate
		$recordCan = $candidate->findAsObject(array("id = "=>$recordResume->can_id));
		$arrMail = array($recordEmp->email,$recordCan->email);
		$strEmp = "Here is the resume that you just follow it in HRCambodia!<br/>";
		$strEmp .="Name : " . $recordResume->rem_name ."<br/>";
		$strEmp .="Date of Birth : " . $recordResume->rem_DOB ."<br/>";
		$strEmp .="Tel : " . $recordResume->rem_tel ."<br/>";
		$strEmp .="Email : " . $recordResume->rem_email ."<br/>";
		$strCan = "Your resume has one company is interested in HRCambodia!<br/>";
		$strCan .="Name : " .$recordEmp->firstname ." ". $recordEmp->lastname ."<br/>";
		$strCan .="Name of Company : " .$recordEmp->company_name ."<br/>";
		$strCan .="Email : " .$recordEmp->email ."<br/>";
		$arrStr = array($strEmp,$strCan);
		$arrSub = array("Resume That You Just Follow With","Who is Follow Your Resume");
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 25;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
			for($i=0;$i<count($arrMail);$i++){
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($arrMail[$i], 'HRCambodia');
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "HRCambodia Alert " . $arrSub[$i];
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $arrStr[$i] . "<br/>");
				$mail->Send();
				$mail->ClearAddresses();
				$mail->ClearAttachments();
			}
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			echo $e->getMessage();
		}*/
	}
	public function unfollow(){
		$membership = $this->loadModel("Membership");
		$resume = $this->loadModel("Resume");
		$employer = $this->loadModel("Employer");
		$candidate = $this->loadModel("Candidate");
		$id = $this->get("id");
		$getResume = $resume->findAsArray(array("id = "=>$id));
		$valmembership = $membership->findObject(array("user_id = "=>$this->emp_session["id"],"sub_type="=>"Employer","resume_id ="=>$getResume["id"]));
		//
		//Send mail to Employer when candidate update Resume
		$recordResume = $resume->findAsObject(array("id = "=>$id));
		//find one record of employer
		$recordEmp = $employer->findAsObject(array("id = "=>$this->emp_session["id"]));
		//find one record of candidate
		$recordCan = $candidate->findAsObject(array("id = "=>$recordResume->can_id));
		$arrMail = array($recordEmp->email,$recordCan->email);
		$strEmp = "Here is the resume that you just unfollow it in HRCambodia!<br/>";
		$strEmp .="Name : " . $recordResume->rem_name ."<br/>";
		$strEmp .="Date of Birth : " . $recordResume->rem_DOB ."<br/>";
		$strEmp .="Tel : " . $recordResume->rem_tel ."<br/>";
		$strEmp .="Email : " . $recordResume->rem_email ."<br/>";
		$strCan = "Your resume has one company is just unfollow in HRCambodia!<br/>";
		$strCan .="Name : " .$recordEmp->firstname ." ". $recordEmp->lastname ."<br/>";
		$strCan .="Name of Company : " .$recordEmp->company_name ."<br/>";
		$strCan .="Email : " .$recordEmp->email ."<br/>";
		$arrStr = array($strEmp,$strCan);
		$artSub = array("Resume That You Just Unfollow With","Who is Unfollow Your Resume");
		
		/* ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			//$mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
			//$mail->AddAddress('physopheak10@gmail.com', '');
			//$mail->AddAddress('phonpisey23@gmail.com','');
				
			for($i=0;$i<count($arrMail);$i++){
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($arrMail[$i], 'HRCambodia');
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "HRCambodia Alert " . $artSub[$i];
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $arrStr[$i] . "<br/>");
				$mail->Send();
				$mail->ClearAddresses();
				$mail->ClearAttachments();
			}
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			echo $e->getMessage();
		} */
		//
		//Update or delete
		$version = $membership->findAsObject(array("user_id = "=>$this->emp_session["id"],"resume_id = "=>$valmembership->resume_id,"sub_type = "=>"Employer"));
		$getDataSave = $membership->update(array("resume_id"=>NULL,"version"=>$version->version + 1),array("user_id = "=>$this->emp_session["id"],"resume_id = "=>$valmembership->resume_id,"sub_type = "=>"Employer"));
		echo 1;
	}
	public function loginFromMail(){
		$this->set(array("pid"=>$this->get("pid")));
		$this->render("login_from_mail");
	}
	public function loginViewCV(){
		$employer = $this->loadModel("User");
		$resume = $this->loadModel("Resume");
		$result = $employer->checkRecord("Employers",array("username","password"),array("username="=>$this->get("username"),"password="=>md5($this->get("password"))));
		if($result){
			@$sessionId = $employer->getValue("Sessions","sessionid",array("userid="=>$this->get("username"),"ip="=>$_SERVER['REMOTE_ADDR']));
			if($sessionId == NULL){
				Session::set("sessionId",$sessionId);
				Session::set("employer_name",$this->get("username"));
				Session::set("employer_id",$employer->getValue("Employers","id",array("username="=>$this->get("username"),"password="=>md5($this->get("password")))));
				$employer->saveUserSession(array(
						"sessionid"=>md5(time().$this->get("username").$_SERVER["REMOTE_ADDR"]),
						"version"=>1,
						"logged"=>date("Y-m-d H:i:s"),
						"ip"=>$_SERVER["REMOTE_ADDR"],
						"userid"=>Session::get("employer_name"),
						"type"=>Configuration::getNodeValue("Employer_Type"),
						"duration"=>Configuration::getNodeValue("Valid_Time")
				));
				$getRemId = $resume->getObject(array("can_id = "=>$this->get("pid")));
				$this->redirect(array("resume"=>"detailcandidat","pid"=>$getRemId->id));
			}else{
				$getRemId = $resume->getObject(array("can_id = "=>$this->get("pid")));
				$check=$employer->checkSession($sessionId,$_SERVER["REMOTE_ADDR"]);
				$check==1?$this->logoutViewCV():$this->redirect(array("resume"=>"detailcandidat","pid"=>$getRemId->id));
			}
		}else{
			$this->set(array("loginerr"=>"login failed !"));
			$this->redirect(array("employer"=>"loginform"));
		}
	}
	public function logoutViewCV(){
		Session::destroy();
		$resume = $this->loadModel("Resume");
		$getRemId = $resume->getObject(array("can_id = "=>$this->get("pid")));
		$this->redirect(array("resume"=>"detailcandidat","pid"=>$getRemId->id));
	}
	public function forgot(){
		$this->render("forgot_pswd");
	}
	public function sendMail(){ 
		$employer = $this->loadModel("Employer");
		$txtMail = $this->get("txtForgot");
		$findObject = $employer->findObject(array("email = "=>$txtMail));
		$date = date("Y-m-d H:i:s");
		$date = strtotime($date);
		$date = strtotime("+1 day" , $date);
		$linkExp = date('Y-m-d H:i:s', $date);
		$this->model->update(array("link_expire"=>$linkExp),array("id="=>$findObject->id));
		if($findObject){
			if($txtMail == $findObject->email){
				$str = "<b>HRCambodia .com Your New Password!</b><br/>";
					$str = "Please, click on this link to reset your password <a href='".SERVER.ROOT."index.php/employer/resetpage/empId:$findObject->id'>click</a>";
				ob_start();
				//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
				Import::util('class.phpmailer');
				//the true param means it will throw exceptions on errors, which we need to catch
				$mail = new PHPMailer(true);
				//telling the class to use SMTP
				$mail->IsSMTP();
				try {
					// SMTP server
					$mail->Host = "mail.atmos-techno.com";
					// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
					$mail->SMTPDebug = 1;
					// enable SMTP authentication
					$mail->SMTPAuth = true;
					// sets the SMTP server
					$mail->Host = "mail.atmos-techno.com";
					// set the SMTP port for the MY OWN DOMAIN server
					$mail->Port = 26;
					// SMTP account username
					$mail->Username = "demo@atmos-techno.com";
					// SMTP account password
					$mail->Password = "demo*123456";
					//$mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
					//$mail->AddAddress('physopheak10@gmail.com', '');
					//$mail->AddAddress('phonpisey23@gmail.com','');
					$email_address = filter_input(INPUT_GET, $findObject->email, FILTER_VALIDATE_EMAIL);
					if (!$email_address) {
						$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
						// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
						$mail->AddAddress($findObject->email, ' ');
						//$mail->AddAddress('phonpisey23@gmail.com','');
						$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
						$mail->Subject = "New Password";
						// optional - MsgHTML will create an alternate automatically
						$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
						$mail->MsgHTML("<h3>Password Information</h3>" . $str . "<br/>");
						$mail->Send();
						$this->refresh(array("page"=>"index"),array(),4);
						echo "Reset password successfully,Please go to your email to reset your password!";
					} else {
						//echo 'Email is invalid...';
						break;
					}
				} catch (phpmailerException $e) {
					//Pretty error messages from PHPMailer
					echo $e->errorMessage();
				} catch (Exception $e) {
					//Boring error messages from anything else!
					echo $e->getMessage();
				}
			}else{
				$this->set(array("message"=>"Email not found on the system. Try again"));
				$this->render("forgot_pswd");
			}
				
		}else{
			$this->set(array("message"=>"Email not found on the system. Try again")); 
			$this->render("forgot_pswd");
		}
	}
	public function adminjobs(){
		$employer = $this->loadModel("Employer");
		$jobs = $this->loadModel("Job");
		if($this->get("id")!=NULL){
			$this->set(array("records"=>$jobs->getEmployerJobs($this->get("id"),1,20) ) );
			$this->render("admin_jobs");
		}else{
			echo "Employer id is not specified.";
		}
	}
	public function adminaccount(){
		$employer = $this->loadModel("Employer");
		$this->set(array("employer"=>$employer->findAsObject(array("id="=>$this->get("id") )) ) );
		$this->render("admin_account");
	}
	//View Job
	/* public function view(){
		$job = $this->loadModel("Job");
		$checkedbox = $this->get("pid");
		if($checkedbox){
			$getfield[]=$job->findObject(array("id="=>$checkedbox));
			$this->set(array("getfield"=>$getfield));
			$category = $this->loadModel("Categorie");
			$this->set(array("jobtime"=>$category->GetJobTime(20)));
			$this->set(array("location"=>$category->GetJobTime(1)));
			$this->set(array("jobcategory"=>$category->GetJobTime(23)));
			$this->set(array("industry"=>$category->GetJobTime(179)));
			$this->set(array("companytype"=>$category->GetJobTime(227)));
			$this->set(array("months"=>$category->GetJobTime(287)));
			$this->set(array("days"=>$category->GetJobTime(255)));
			//Facebook
			$facebook = $this->loadModel("Facebook");
			$this->set(array("share"=>array("data-href"=>$_SESSION['fullURL'],
					"data-type"=>"button_count")));
			unset($_SESSION['fullURL']);
			$this->set(array("layout"=>"view"));
			$this->render("admin");
		}else {
			$this->render("admin_edit_post");
		}
	} */
}